<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Chat</title>
</head>
<body>
<input id="text" type="text" />
<button onclick="send()" >Send</button>
<button onclick="closeWs()" >Close</button>
<div id="message"></div>

<script type="text/javascript">
    var webSocket = null;

    if ('WebSocket' in window) {
        webSocket = new WebSocket("ws://localhost:80/p2p");
    } else {
        alert("Not support websocket")
    }

    webSocket.onerror = function () {
        setMessageInnerHtml("服务器通信故障");
    }

    //连接成功回调方式
    webSocket.onopen = function (event) {
        setMessageInnerHtml("服务器连接成功");
    }
    //收到消息回调方式
    webSocket.onmessage = function (event) {
        setMessageInnerHtml(event.data);
    }

    //连接关闭回调方式
    webSocket.onclose = function (event) {
        setMessageInnerHtml("服务器连接已关闭");
    }

    //窗口关闭进，主动关闭Websocket
    window.onbeforeunload = function () {
        webSocket.close();
    }

    function setMessageInnerHtml(innerHtml) {
        document.getElementById("message").innerHTML += innerHtml + "<br/>";
    }

    function send() {
        var msg = document.getElementById("text").value;
        webSocket.send(msg);
    }

    function closeWs() {
        webSocket.close();
    }

</script>
</body>
</html>